package com.hzhc.service.impl;


import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.HcMethodUtil;
import com.hzhc.entity.ChargeConfig;
import com.hzhc.entity.ChargeContractDetail;
import com.hzhc.entity.CntrChargeDetail;
import com.hzhc.entity.CompanyInfo;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.ChargeConfigMapper;
import com.hzhc.mapper.ChargeContractDetailMapper;
import com.hzhc.mapper.SysDictMapper;
import com.hzhc.service.ChargeConfigService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.ChargeConfigVo;
import com.hzhc.vo.ChargeItemVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 计费项配置 服务实现类
 * </p>
 *
 * @author dengx
 * @since 2022-09-22
 */
@Service
@RequiredArgsConstructor
public class ChargeConfigServiceImpl extends ServiceImpl<ChargeConfigMapper, ChargeConfig> implements ChargeConfigService {

    private final SysDictMapper sysDictMapper;
    private final ChargeConfigMapper configMapper;
    private final ChargeContractDetailMapper chargeContractDetailMapper;


    @Override
    public List<ChargeConfigVo> selectChargeConfig(Page<ChargeConfigVo> page, ChargeConfigVo chargeConfig) {
        IPage<ChargeConfigVo> list = configMapper.selectChargeConfigPage(page, chargeConfig);
        return list.getRecords();
    }

    @Override
    public ResultUtil<T> saveChargeConfig(ChargeConfig chargeConfig) {
        QueryWrapper<ChargeConfig> queryWrapper = new QueryWrapper<ChargeConfig>();
        queryWrapper.eq("disable", 0);
        queryWrapper.eq("charge_item_id", chargeConfig.getChargeItemId());
        queryWrapper.eq("charge_work_item_id", chargeConfig.getChargeWorkItemId());
        if (!configMapper.selectList(queryWrapper).isEmpty()) {
            return ResultUtil.fail();
        }
        chargeConfig.setCreateTime(LocalDateTime.now());
        boolean b = save(chargeConfig);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public Boolean delChargeConfig(Long id) {
        ChargeConfig chargeConfig = getById(id);
        chargeConfig.setDisable(true);
        chargeConfig.setUpdateTime(LocalDateTime.now());
        return updateById(chargeConfig);
    }

    @Override
    public List<ChargeConfigVo> selectWorkItemConfigList(Page<ChargeConfig> page, ChargeConfigVo chargeConfigVo) {
        IPage<ChargeConfigVo> list = configMapper.selectChargeConfigPage1(page, chargeConfigVo);
        return list.getRecords();
    }

    @Override
    public ResultUtil<T> saveWorkItemConfig(ChargeConfig chargeConfig) {
        QueryWrapper<ChargeConfig> queryWrapper = new QueryWrapper<ChargeConfig>();
        queryWrapper.eq("disable", 0);
        queryWrapper.eq("work_item_id", chargeConfig.getWorkItemId());
        queryWrapper.eq("dict_id", chargeConfig.getDictId());
        if (!configMapper.selectList(queryWrapper).isEmpty()) {
            return ResultUtil.build(ResultUtilCodeEnum.WORKITEM_IS_EXIST);
        }
        chargeConfig.setCreateTime(LocalDateTime.now());
        boolean b = save(chargeConfig);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> checkChargeItemField(ChargeConfig chargeConfig) {
        if (chargeConfig != null &&chargeConfig.getChargeItemId()   != null) {
            int i = count(Wrappers.<ChargeConfig>lambdaQuery()
                    .eq(ChargeConfig::getChargeItemId, chargeConfig.getChargeItemId())
                    .eq(ChargeConfig::getDisable, 0)
                    .ne(chargeConfig.getId() != null, ChargeConfig::getId, chargeConfig.getId())
                    .eq(ChargeConfig::getChargeWorkItemId, chargeConfig.getChargeWorkItemId()));
            if (i > 0) {
                return ResultUtil.build(ResultUtilCodeEnum.ITEM_IS_EXIST);
            }
        }
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil<T> checkWorkItemId(ChargeConfig chargeConfig) {
        if (chargeConfig != null && chargeConfig.getWorkItemId()  != null) {
            int i = count(Wrappers.<ChargeConfig>lambdaQuery()
                    .eq(ChargeConfig::getWorkItemId, chargeConfig.getWorkItemId())
                    .eq(ChargeConfig::getDisable, 0)
                    .ne(chargeConfig.getId() != null, ChargeConfig::getId, chargeConfig.getId())
                    .eq(ChargeConfig::getDictId, chargeConfig.getDictId()));
            if (i > 0) {
                return ResultUtil.build(ResultUtilCodeEnum.WORKITEM_IS_EXIST);
            }
        }
        return ResultUtil.ok();
    }

    @Override
    public List<ChargeConfig> getListByName(String name) {
        return baseMapper.getListByName(name);
    }

    /**
     * 集装箱计算作业费用
     *
     * @param chargeItemVos
     */
    public List<CntrChargeDetail> comCalculateCntrCost(List<ChargeItemVo> chargeItemVos, CntrChargeDetail chargeDetail
            , Long contractId, CompanyInfo companyInfo) {
        List<CntrChargeDetail> returnList = new ArrayList<>();
        for (ChargeItemVo chargeItemVo : chargeItemVos) {
            CntrChargeDetail cntrChargeDetail=new CntrChargeDetail();
            BeanUtils.copyProperties(chargeDetail, cntrChargeDetail);
            if (companyInfo!=null){
                cntrChargeDetail.setCompanyId(companyInfo.getId().intValue());
                cntrChargeDetail.setCompanyName(companyInfo.getName());
            }
            cntrChargeDetail.setChargeItemId(chargeItemVo.getId().intValue());
            cntrChargeDetail.setChargeItemName(chargeItemVo.getName());
            cntrChargeDetail.setChargeType(chargeItemVo.getType());
            //获取计费属性和计费费率
            List<ChargeContractDetail> chargeContractDetails = chargeContractDetailMapper.selectList(Wrappers.<ChargeContractDetail>lambdaQuery()
                    .eq(ChargeContractDetail::getItemId, chargeItemVo.getId())
                    .eq(ChargeContractDetail::getContractId, contractId)
                    .eq(ChargeContractDetail::getDisable, 0));
            for (ChargeContractDetail chargeContractDetail : chargeContractDetails) {
                String peice = chargeContractDetail.getPrice();
                String realPrice = "";
                String elementJson = chargeContractDetail.getElementJson();
                JSONObject jsonObject = JSONObject.parseObject(elementJson);
                //遍历json的key,value
                boolean istrue = true;
                for (Map.Entry<String, Object> jsonObjectEntry : jsonObject.entrySet()) {
                    String smethodName = HcMethodUtil.getGetMethod(cntrChargeDetail, jsonObjectEntry.getKey());
                    if (StrUtil.isNotBlank(smethodName)) {
                        Object sobj = ReflectUtil.invoke(cntrChargeDetail, smethodName);
                        if (sobj == null || StrUtil.isBlank((String) jsonObjectEntry.getValue())) {
                            continue;
                        }
                        if (!"查验掏箱费".equals(chargeItemVo.getName())) {
                            if ("getCntrSize".equals(smethodName) && jsonObjectEntry.getValue().equals(cntrChargeDetail.getCntrSize().substring(0,2))) {
                                realPrice = String.valueOf(Integer.valueOf(peice));
                            } else {
                                istrue = false;
                                break;
                            }
                        } else {
                            if ("getUnloadingVolume".equals(smethodName) && jsonObjectEntry.getValue().equals(cntrChargeDetail.getUnloadingVolume())
                                    && jsonObject.get("cntrSize").equals(cntrChargeDetail.getCntrSize())) {
                                realPrice = String.valueOf(Integer.valueOf(peice));
                                break;
                            } else {
                                istrue = false;
                                break;
                            }
                        }
                    }
                }
                if (istrue) {
                    if (StrUtil.isNotBlank(realPrice)) {
                        cntrChargeDetail.setPrice(realPrice);
                    } else {
                        cntrChargeDetail.setPrice(peice);
                    }
                }
            }

            if (StrUtil.isBlank(cntrChargeDetail.getPrice())) {
                cntrChargeDetail.setPrice("0");
            }
            cntrChargeDetail.setCreateTime(LocalDateTime.now());
            returnList.add(cntrChargeDetail);

        }
        return returnList;
    }
}




